import React, { useEffect, useState } from 'react'
import styles from './index.module.scss'
import { Modal, Input, Carousel, Button, Image, Avatar, Form, Dropdown, message } from 'antd'
import { HeartFilled, HeartOutlined, StarOutlined, StarFilled, UserOutlined, DeleteOutlined, EllipsisOutlined } from '@ant-design/icons'
import { getLs, getTimer } from '@/common/common'
import { addReview, getDetail, sendCollection, sendHeart, updateFans, findReviewList, delReview, updateArea, deletePublic, setTopReviewApi, getTopReviewApi, delTopReviewApi } from '@/common/api'
import _ from 'lodash'
import notReview from '@/assets/home/not_review.png'
import UsePaginatedHook from '@/components/ComponentHook/UsePaginatedHook'

const { TextArea } = Input;
export default function CardModal(props) {
    const { modalOpen, publicId, isUser, authorInfo, pubLicist, setPublicList } = props
    const userInfo = getLs('userInfo') || { _id: '', name: '' }
    const { _id: userId, name, avator } = userInfo
    const [TextInfo, setTextInfo] = useState({})
    const [loading, setLoading] = useState(false)
    const [btnLoading, setBtnLoading] = useState(false)
    // 是否关注按钮
    const [isAttention, setAttention] = useState(false)
    const [form] = Form.useForm()
    // 判断有没有点过赞和带你赞个数
    const [likeType, setLikeType] = useState({})
    const [collectType, setCollectType] = useState({})
    const [area, setArea] = useState(1)
    const [topReview, setReview] = useState(null)
    const [topId,setTopId]=useState("")
    // 获取评论列表
    const { list, endRef, setList } = UsePaginatedHook(findReviewList, 15, { publicId })
    useEffect(() => {
        console.log(Boolean(topReview));
        if (modalOpen) {
            getPublicDetail()
            getTopReview()
        }
    }, [modalOpen])

    // 获取详情
    const getPublicDetail = async () => {
        !modalOpen && setLoading(true)
        try {
            const RES = await getDetail({ userId, publicId })
            if (RES.code === 200) {
                setLikeType(_.get(RES, 'data.likeType'))
                setCollectType(_.get(RES, 'data.collectType'))
                setTextInfo(_.get(RES, 'data'))
                setAttention(_.get(RES, 'data.payFor'))
                setArea(_.get(RES, 'data.area'))
                !modalOpen && setLoading(false)
            }
        } catch (error) {

        }
    }
    // 发送评论
    const sendReview = () => {
        form.validateFields().then(async (values) => {
            const { review: text } = values
            const time = getTimer(Math.floor(Date.now() / 1000))
            const params = {
                publicId,
                userId,
                avator,
                name,
                text,
                time
            }
            try {
                const RES = await addReview(params)
                if (RES.code === 200) {
                    setList(pre => [
                        {
                            operatorId: userId,
                            name,
                            text,
                            time,
                            avator,
                            _id: RES.data._id

                        }, ...pre])
                    form.resetFields()
                    message.success(RES.msg)
                }
            } catch (error) {
                return error
            }
        }).catch(err => {
            console.log(err);
        })
    }
    // 点赞
    const updateHeart = async (type) => {
        const RES = await sendHeart({ publicId, userId, type })
        if (RES.code === 200) {
            setLikeType(RES.data)
            message.success(RES.msg)
        }
    }
    // 收藏
    const addCollect = async (type) => {
        const RES = await sendCollection({ publicId, userId, type })
        if (RES.code === 200) {
            setCollectType(RES.data)
            message.success(RES.msg)
        }
    }
    // 关注
    const Attention = async (type) => {
        const timer = Math.floor(Date.now() / 1000)
        const data = {
            otherId: TextInfo.userId,
            userId,
            timer,
            type
        }
        try {
            setBtnLoading(true)
            const RES = await updateFans(data)
            setBtnLoading(false)
            if (RES.code === 200) {
                setAttention(RES.data.payFor)
                // 发送socket
                // socket.onopen(()=>{
                //     socket.send("我点赞了")
                // })
                message.success(_.get(RES, 'data.msg'))
            }
        } catch (error) {
            return error
        }
    }
    // 暂无评论
    const noReview = () => {
        return <div className='no-review'>
            <Image preview={false} src={notReview} />
            <p>暂无评论</p>
        </div>
    }
    // 删除评论
    const delReviw = async (value) => {
        const { _id: reviewId } = value
        try {
            const RES = await delReview({ userId, reviewId, publicId })
            if (RES.code === 200) {
                setList(list.filter(item => item._id !== reviewId))
                message.success("删除成功!")
            }
        } catch (error) {

        }
    }
    // 设置为私密或公开
    const checkArea = async (value) => {
        const RES = await updateArea({ publicId, area: value })
        if (RES.code === 200) {
            setArea(value)
            setPublicList(pre => {
                return pre.map(item => {
                    if (item.publicId === publicId) {
                        return {
                            ...item,
                            area: value
                        }
                    }
                    return item
                })
            })
            message.success("设置成功!")
        }
    }
    //删除作品
    const delPublic = async () => {
        const RES = await deletePublic({ publicId, userId })
        if (RES.code === 200) {
            props.setModalOpen()
            if (isUser) {//个人笔记
                setPublicList(pre => {
                    return pre.filter(item => item.publicId !== publicId)
                })
            }
            message.success(RES.msg)
        }
    }
    // 设置置顶评论
    const setTopReview = async (item) => {
        const data = {
            publicId,
            _id:item._id
        }
        const RES = await setTopReviewApi(data)
        if (RES.code === 200) {
            setReview(item)
            setTopId(item._id)
        }
    }
    //取消置顶
    const delTopReview = async (item) => {
        const data = {
            publicId,
            _id:item._id
        }
        const RES = await delTopReviewApi(data)
        if (RES.code === 200) {
            setReview(null)
            setTopId('')
            message.success(RES.msg)
        }
    }
    // 获取指定评论
    const getTopReview = async() => {
        const RES = await getTopReviewApi({ publicId })
        if (RES.code === 200&&Object.keys(RES.data).length!==0) {
            setReview(RES.data)
            setTopId(RES.data.id)
        }
    }
    return (
        <>
            <Modal
                className={styles.CardModal}
                closable={false}
                width={1000}
                centered
                loading={loading}
                open={props.modalOpen}
                footer={null}
                onCancel={() => props.setModalOpen()}
            >
                <div style={{ display: "flex", height: '850px' }}>
                    <div className='left'>
                        <Carousel arrows>
                            {TextInfo.imgList && TextInfo.imgList.map((ele, index) => {
                                return <div key={index} className='imgCard'>
                                    <Image style={{ width: '600px', height: '850px', objectFit: 'cover' }} src={`http://localhost:5000/${ele}`} />
                                </div>
                            })}
                        </Carousel>
                    </div>
                    <div className='right'>
                        {isUser && <Dropdown menu={{
                            items: [
                                {
                                    label: area === 1 ? <div onClick={() => checkArea(0)}>设为私密作品</div> : <div onClick={() => checkArea(1)}>设为公开作品</div>,
                                    key: `${area}`,
                                },
                                {
                                    label: <div onClick={delPublic}>删除作品</div>,
                                    key: '2',
                                }
                            ]
                        }}
                            trigger={['click']}
                            placement="topRight"
                        >
                            <EllipsisOutlined className='delPublic' />
                        </Dropdown>}

                        {Boolean(authorInfo?._id !== userId) && Boolean(!isUser) && (<div className='top'>
                            <div className='TopLeft'>
                                {Boolean(authorInfo?.avator) ? <Avatar src={`http://localhost:5000/${authorInfo?.avator}`} /> : <Avatar icon={<UserOutlined />} />}
                                <h3>{authorInfo?.name}</h3>
                            </div>
                            <div className='TopRight'>
                                {isAttention ? <Button loading={btnLoading} onClick={() => Attention(isAttention)}>已关注</Button> : <Button loading={btnLoading} type='primary' danger onClick={() => Attention(isAttention)}>关注</Button>
                                }
                            </div>
                        </div>)}
                        <div className='text'>
                            <h3>{TextInfo?.title || ''}</h3>
                            {TextInfo.text && TextInfo.text.split('\n').map((ele, index) => <p key={index}>{ele}</p>)}
                            <div style={{ display: "flex", alignItems: "center" }}>
                                <p style={{ color: "#858585", marginRight: "120px" }}>{getTimer(TextInfo?.time)}</p>
                                <p style={{ marginRight: "20px", cursor: "pointer", fontSize: "16px" }}>
                                    {likeType.type !== 'exist' ? <HeartOutlined onClick={() => updateHeart(likeType.type)} style={{ marginRight: "5px" }} /> : <HeartFilled onClick={() => updateHeart(likeType.type)} style={{ marginRight: "5px", color: "red" }} />
                                    }                                    <label >{likeType.likeNumber}</label>
                                </p>
                                <p style={{ cursor: "pointer", fontSize: "16px" }}>
                                    {collectType.type !== 'exist' ? <StarOutlined onClick={() => addCollect(collectType.type)} style={{ marginRight: "5px" }} /> : <StarFilled onClick={() => addCollect(collectType.type)} style={{ marginRight: "5px", color: "#ff9a00" }} />}
                                    <label >{collectType.collectNumber}</label>
                                </p>
                            </div>
                        </div>
                        <div className='review'>
                            {Boolean(topReview) && (
                                <div key={topReview.id} className='item'>
                                    <div className='reviewLeft'>
                                        <div className='reviewImg'>
                                            {topReview.avator ? <Avatar src={`http://localhost:5000/${topReview.avator}`} /> : <Avatar icon={<UserOutlined />} />}
                                        </div>
                                    </div>
                                    <div className='reviewRight'>
                                        <p>{topReview.name}</p>
                                        <p>{topReview.text}</p>
                                        <p style={{ color: "rgba(51,51,51,0.6)" }}>
                                            <span>{topReview.time}</span>
                                            {isUser && <DeleteOutlined onClick={() => delReviw(topReview)} />}
                                            {isUser && <Dropdown menu={{
                                                items: [
                                                    {
                                                        label: <span onClick={()=>delTopReview(topReview)}>取消置顶</span>,
                                                        key: '1',
                                                    }
                                                ]
                                            }}
                                                trigger={['click']}
                                                placement="bottom"
                                            >
                                                <EllipsisOutlined className='delPublic' />
                                            </Dropdown>}
                                        </p>
                                    </div>
                                    <div className='topReview'>置顶</div>
                                </div>
                            )
                            }
                            {list.length === 0 ? noReview() : list?.map((item, index) => {
                                return <div  style={{display:Boolean(topId===item._id)?'none':'block'}}>
                                     <div key={item._id} ref={list.length === index + 1 ? endRef : null} className='item'>
                                <div className='reviewLeft'>
                                    <div className='reviewImg'>
                                        {item.avator ? <Avatar src={`http://localhost:5000/${item.avator}`} /> : <Avatar icon={<UserOutlined />} />}
                                    </div>
                                </div>
                                <div className='reviewRight'>
                                    <p>{item.name}</p>
                                    <p>{item.text}</p>
                                    <p style={{ color: "rgba(51,51,51,0.6)" }}>
                                        <span>{item.time}</span>
                                        {isUser && <DeleteOutlined onClick={() => delReviw(item)} />}
                                        {isUser && <Dropdown menu={{
                                            items: [
                                                {
                                                    label: <span onClick={()=>setTopReview(item)}>设为置顶</span>,
                                                    key: '1',
                                                }
                                            ]
                                        }}
                                            trigger={['click']}
                                            placement="bottom"
                                        >
                                            <EllipsisOutlined className='delPublic' />
                                        </Dropdown>}
                                    </p>

                                </div>
                            </div>
                                </div>
                            }
                            )
                            }
                        </div>
                        <div className='publish'>
                            <Form
                                form={form}
                                name="validateOnly"
                            >
                                <Form.Item
                                    name="review"
                                    rules={[
                                        {
                                            required: true,
                                            message: "输入内容不能为空",
                                            validator: (_, value) => {
                                                if (!value.trim()) {
                                                    return Promise.reject()
                                                }
                                                return Promise.resolve()
                                            }
                                        }
                                    ]}
                                >
                                    <TextArea placeholder='说点什么吧...' autoSize />
                                </Form.Item>
                            </Form>
                            <Button onClick={sendReview}>发布</Button>
                        </div>
                    </div>
                </div>
            </Modal>
        </>
    )
}
